package org.wlgzs.moyue.service.servicelmpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.wlgzs.moyue.dao.BookDao;
import org.wlgzs.moyue.dao.BookListDao;
import org.wlgzs.moyue.dao.ConsumeDao;
import org.wlgzs.moyue.dao.UserDao;
import org.wlgzs.moyue.entity.Book;
import org.wlgzs.moyue.entity.BookList;
import org.wlgzs.moyue.entity.Consume;
import org.wlgzs.moyue.entity.User;
import org.wlgzs.moyue.service.ConsumeService;
import org.wlgzs.moyue.util.Result;
import org.wlgzs.moyue.util.ResultCode;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ConsumeServiceImpI implements ConsumeService {
    @Autowired
    ConsumeDao consumeDao;
    @Autowired
    BookListDao bookListDao;
    @Autowired
    UserDao userDao;
    @Autowired
    BookDao bookDao;
    @Autowired
    ConsumeService consumeService;

    @Override
    public String reward(User user, Long bookId, int virtualCurrency) {
        Long userMoney = user.getUserRewards();
        Long afterMoney = Math.abs(userMoney - virtualCurrency);
        if (virtualCurrency > userMoney) {
            return userMoney + "," + afterMoney;
        } else {
            user.setUserRewards(afterMoney);
            Consume consume = new Consume();
            consume.setUserId(user.getUserId());
            consume.setConsumeMoney(virtualCurrency);
            consume.setConsumeType("打赏");
            consume.setConsumeObjectId(bookId);
            consume.setIsShow(1);
            Date date = new Date();
            consume.setConsumeDate(date);
            consumeDao.save(consume);
            userDao.save(user);
            return "1";
        }
    }

    @Override
    public String buychapters(Long[] chapters, Long userId) {
        User user = userDao.findById(userId).get();
        List<Integer> orderInteger = new ArrayList<>();
        String roleId = user.getRoleId();
        Long userMoney = user.getUserRewards();
        // String [] arr = chapters.split(",");
        BookList ch = bookListDao.findByBookListId(chapters[0]);
        Long bookId = ch.getBookId();
        Consume consume = new Consume();
        Date date = new Date();
        Book book = bookDao.findById(bookId).get();
        int count = bookListDao.countByBookId(bookId);
        consume.setConsumeDate(date);
        consume.setIsShow(1);
        consume.setUserId(userId);
        consume.setConsumeObjectId(bookId);
        consume.setConsumeType("消费");
        int bookMoney = 0;
        Long afterUserMoney;
        for (int i = 0; i < chapters.length; i++) {
            BookList chapts = bookListDao.findByBookListId(chapters[i]);
            orderInteger.add(chapts.getBookListOrder());
            bookMoney += chapts.getChapterPrice();
        }
        if (count == chapters.length) {
            System.out.println("1");
            consume.setConsumeNote("*");
        } else {
            System.out.println("2");
            String string = "";
            for (Integer orderId :orderInteger
                    ) {
                string += orderId + ",";

            }
            consume.setConsumeNote(string);
        }
        if (userMoney < bookMoney) {
            Long surplus = bookMoney-userMoney;
            return userMoney+","+surplus ;
        } else {
            if (roleId.equals("2")) {
                afterUserMoney = userMoney - (int) (bookMoney * 0.8);
                consume.setConsumeMoney((int)(bookMoney*0.8));
            } else if (roleId.equals("3")) {
                afterUserMoney = userMoney - (int) (bookMoney * 0.6);
                consume.setConsumeMoney((int)(bookMoney*0.6));
            } else {
                afterUserMoney = userMoney - bookMoney;
                consume.setConsumeMoney(bookMoney);
            }
            user.setUserRewards(afterUserMoney);
            userDao.save(user);
            consumeDao.save(consume);
        }
        return "ok";
    }

    @Override
    public boolean isBuyed(long chapterId, long bookId, HttpSession session) {
        BookList bookList = bookListDao.findByBookListId(chapterId);
        int chapterOrder = bookList.getBookListOrder();
        User user = (User) session.getAttribute("user");
        if (chapterOrder <= 30) {
            System.out.println(1);
            return true;

        } else if (user == null) {
            System.out.println(2);
            return false;
        }
        List<Consume> consumeList = consumeDao.findByUserIdAndConsumeObjectIdAndConsumeType(user.getUserId(), bookId, "消费");
        if (consumeList == null) {
            System.out.println(3);
            return false;
        }
        String string = "";
        for (Consume consume : consumeList
                ) {
            string += consume.getConsumeNote();
            System.out.println(consume.getConsumeNote());
        }
        System.out.println(string);
        String[] strings = string.split(",");
        for (String str : strings
                ) {
            System.out.println(str);
            if (str.equals("*") || str.equals(Integer.toString(chapterOrder))) {
                System.out.println(4);
                return true;
            }
        }
        System.out.println(5);
        return false;
    }

    @Override
    public void showFinancial(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        User currentUser = userDao.findById(user.getUserId()).get();
        model.addAttribute("money", currentUser.getUserRewards());
        List<Consume> consumeList = consumeDao.findByConsumeTypeAndUserIdOrderByConsumeDateDesc("充值", user.getUserId());
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "consumeDate");
        Sort sort = new Sort(order);
        List<Consume> consumeList1 = consumeDao.getUserComsumes("消费", "打赏", 1,user.getUserId(), sort);
        model.addAttribute("chongzhi", consumeList);
        model.addAttribute("consume", consumeList1);
    }

    public Result jundgeReward(String virtualCurrency, Long bookId, HttpSession session) {
        User user = (User) session.getAttribute("user");
        String jundge = "1";
        int currency;
        int virtualSize = virtualCurrency.length();
        if (virtualCurrency.charAt(virtualSize - 1) == '万') {
            String str = virtualCurrency.substring(0, virtualCurrency.length() - 1);
            currency = Integer.parseInt(str) * 10000;
        } else {
            currency = Integer.parseInt(virtualCurrency);
        }
        String isTure = consumeService.reward(user, bookId, currency);
        if (jundge.equals(isTure)) {
            return new Result(ResultCode.SUCCESS, "打赏成功");
        } else {
            return new Result(ResultCode.NOMONEY, isTure);
        }
    }

    @Override
    public void deleteConsume(Long consumeId) {
        consumeDao.deleteById(consumeId);
    }

    @Override
    public void deleteConsumes(Long[] consumesId){
        for (Long consumeId:consumesId
             ) {
            consumeDao.deleteById(consumeId);
        }
    }

}
